package com.iqilu.ksd.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.iqilu.ksd.R;
import com.iqilu.ksd.bean.GalleryItemBean;
import com.iqilu.ksd.bean.NewsBean;
import com.iqilu.ksd.bean.PaikeBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.utils.ShareUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.util.ArrayList;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import okhttp3.Call;
import okhttp3.Request;

/**
 * Created by Coofee on 2016/12/26.
 */

public class PaikeActivity extends BaseActivity {

    private static final String TAG = "PaikeActivity";

    private int id;
    private PaikeBean data;
    private String mUrl;

    private WebView wvContent;
    private ImageView btBack;
    private ImageView btShare;
    private ImageView btLove;
    private LinearLayout layComment;
    private LinearLayout layLike;
    private ProgressBar pbBar;
    private RelativeLayout layLoading;

    private static final int PER_STORAGE = 101;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_paike);
        ShareSDK.initSDK(this);
        id = getIntent().getIntExtra("id", 0);
        initView();
        initWebView();
    }

    private void initView() {
        wvContent = getView(R.id.wv_content);
        btBack = getView(R.id.bt_back);
        btShare = getView(R.id.bt_share);
        btLove = getView(R.id.bt_love);
        layComment = getView(R.id.lay_comment);
        layLike = getView(R.id.lay_like);
        pbBar = getView(R.id.pb_bar);
        layLoading = getView(R.id.lay_loading);

        btLove.setVisibility(View.INVISIBLE);
        layComment.setVisibility(View.INVISIBLE);
        layLike.setVisibility(View.INVISIBLE);

        btBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toShare();
            }
        });

    }

    private void initWebView() {
        WebSettings settings = wvContent.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setSupportZoom(false);
        settings.setBuiltInZoomControls(false);
        String ua = settings.getUserAgentString();
        settings.setUserAgentString(ua + ";shandian/android");
        wvContent.addJavascriptInterface(new JsObject(getApplicationContext()), "imagelistner");
        wvContent.setWebChromeClient(new MyWebChromeClient());
        wvContent.setWebViewClient(new MyWebViewClient());
        getContent();
    }

    private class MyWebChromeClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress != 100) {
                pbBar.setProgress(newProgress);
            }
            super.onProgressChanged(view, newProgress);
        }
    }

    private void toShare() {
        Platform.ShareParams sp = new Platform.ShareParams();
        sp.setTitle(data.getTitle());
        sp.setTitleUrl(data.getShareurl()); // 标题的超链接
        sp.setText(data.getDescription());
        sp.setSiteUrl(data.getShareurl());
        sp.setUrl(data.getShareurl());
        sp.setImageUrl(data.getThumb());//分享网络图片
        sp.setSite(getString(R.string.app_name));
        ShareUtils.getInstance().setShareParams(this, sp).show();
    }

    private void getContent() {
        String url = Api.URL_CLUE_SHOW + "?id=" + id;
        OkHttpUtils.get().url(url).build().execute(new StringCallback() {

            @Override
            public void onBefore(Request request, int id) {
                super.onBefore(request, id);
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                Toast.makeText(PaikeActivity.this, R.string.content_null, Toast.LENGTH_SHORT).show();
//                layLoading.setVisibility(View.GONE);
            }

            @Override
            public void onResponse(String response, int id) {
                layLoading.setVisibility(View.GONE);
                data = JSONUtils.requestDetail(response, "data", PaikeBean.class);
                if (data == null) {
                    Toast.makeText(PaikeActivity.this, R.string.content_null, Toast.LENGTH_SHORT).show();
                    return;
                }
                wvContent.loadDataWithBaseURL(null, data.getContent(), "text/html", "utf-8", null);
                wvContent.setVisibility(View.VISIBLE);
            }
        });
    }

    public class MyWebViewClient extends WebViewClient {
        @Override
        public void onPageFinished(WebView view, String url) {
            view.getSettings().setJavaScriptEnabled(true);
            super.onPageFinished(view, url);
            addImageClickListner();
            wvContent.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            view.getSettings().setJavaScriptEnabled(true);
            super.onPageStarted(view, url, favicon);
        }
    }

    public class JsObject {

        private Context context;

        public JsObject(Context context) {
            this.context = context;
        }

        @JavascriptInterface
        public void openImage(String img, String position) {
            NewsBean news = new NewsBean();
            String[] imgs = img.split(",");
            ArrayList<GalleryItemBean> gallery = new ArrayList<GalleryItemBean>();
            for (String s : imgs) {
                GalleryItemBean galleryItemBean = new GalleryItemBean();
                galleryItemBean.setImg(s);
                gallery.add(galleryItemBean);
            }
            news.setGallery(gallery);
            news.setTitle(data.getTitle());
            news.setShareurl(data.getShareurl());
            news.setDescription(data.getDescription());
            news.setThumb(data.getThumb());
            Intent intent = new Intent(context, GalleryActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable("news", news);
            intent.putExtras(bundle);
            intent.putExtra("position", Integer.valueOf(position));
            intent.putExtra("fromPaike", true);
            startActivity(intent);
        }
    }

    private void addImageClickListner() {
        wvContent.loadUrl("javascript:(function(){"
                + "var objs = document.getElementsByTagName(\"img\");"
                + "var imgurl=''; "
                + "var j = 0;"
                + "for(var i=0;i<objs.length;i++)  "
                + "{"
                + "if(objs[i].getAttribute('name') == 'videotag') continue;"
                + "imgurl+=objs[i].src+',';"
                + "objs[i].setAttribute('position',j);"
                + "j++;"
                + "    objs[i].onclick=function()  " + "    {  "
                + "        window.imagelistner.openImage(imgurl,this.getAttribute('position'));  "
                + "    }  "
                + "}"
                + "})()");
    }


}
